package com.yhsimon.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.yhsimon.pojo.User;
import com.yhsimon.utils.JsonUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

//@Controller
@RestController
public class UserController {

    @RequestMapping("/json1")
    //@ResponseBody   与@Controller组合使用
    public String json1(){
        ObjectMapper mapper = new ObjectMapper();
        User user = new User(1, "张三", "男");
        String string = null;
        try {
            string = mapper.writeValueAsString(user);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return  string;
    }


    @RequestMapping("/json2")
    public String json2(){
        //创建一个Jackson的对象映射器，用来解析数据
        ObjectMapper mapper = new ObjectMapper();
        List<User> users=new ArrayList<>();
        User user1 = new User(1, "赵六", "女");
        User user2 = new User(1, "赵六", "女");
        User user3 = new User(1, "赵六", "女");
        users.add(user1);
        users.add(user2);
        users.add(user3);
        String str = null;
        try {
            str = mapper.writeValueAsString(users);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return str;
    }


    @RequestMapping("/json3")
    public String json3() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        Date date = new Date();
        String str = mapper.writeValueAsString(date);//返回的是时间戳
        return str;
    }

    @RequestMapping("/json4")
    public String json4() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        //关闭时间戳方式
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
        //自定义日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //指定日期格式
        mapper.setDateFormat(sdf);

        Date date = new Date();
        String str = mapper.writeValueAsString(date);
        return str;
    }

    @RequestMapping("/json5")
    public String json5(){
        return JsonUtils.getJson(new Date());
    }
}
